package com.wufeng.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wufeng.dto.R;
import com.wufeng.entity.PersonInfo;
import com.wufeng.service.PersonInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 *  个人信息(PersonInfo)表控制层
 */
@RestController
@RequestMapping("/personinfo")
public class PersonInfoController {

    @Autowired
    private PersonInfoService personInfoService;

    /**
     * 根据用户id获取个人信息
     * @param userId
     * @return
     */
    @GetMapping("/getPersonInfoByUserId")
    public R getPersonInfoByUserId(@RequestParam("userId") int userId) {
        PersonInfo personInfo = personInfoService.getOne(new QueryWrapper<PersonInfo>().eq("userId", userId));
        Map<String, Object> map = new HashMap<>();
        map.put("personInfo", personInfo);
        return R.ok(map);
    }


    /**
     * 更新个人信息
     * @param personInfo
     * @return
     */
    @PostMapping("/updatePersonInfoByUserId")
    @Transactional
    public R updatePersonInfoByUserId(@RequestBody PersonInfo personInfo) {
        PersonInfo info = personInfoService.getOne(new QueryWrapper<PersonInfo>().eq("userId", personInfo.getUserid()));
        if(info == null){
            // 新增
            boolean save = personInfoService.save(personInfo);
            Map<String, Object> map = new HashMap<>();
            map.put("isUpdate", save);
            return R.ok(map);
        }

        boolean isUpdate = personInfoService.update(personInfo,new QueryWrapper<PersonInfo>().eq("userId", personInfo.getUserid()));
        Map<String, Object> map = new HashMap<>();
        map.put("isUpdate", isUpdate);
        return R.ok(map);
    }
}
